package com.haoxuer.discover.storage.data.dao.impl;

import com.haoxuer.discover.data.core.CriteriaDaoImpl;
import com.haoxuer.discover.data.core.Finder;
import com.haoxuer.discover.storage.data.dao.FileEntityDao;
import com.haoxuer.discover.storage.data.entity.FileEntity;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by imake on 2018年07月09日09:23:15.
 */
@Repository

public class FileEntityDaoImpl extends CriteriaDaoImpl<FileEntity, Long> implements FileEntityDao {
  
  @Override
  public FileEntity findById(Long id) {
    if (id == null) {
      return null;
    }
    return get(id);
  }
  
  @Override
  public FileEntity findByName(String name) {
    Finder finder = Finder.create();
    finder.append("from FileEntity f where f.name=:name");
    finder.setParam("name", name);
    return findOne(finder);
  }
  
  @Override
  public FileEntity save(FileEntity bean) {
    
    getSession().save(bean);
    
    
    return bean;
  }
  
  @Override
  public FileEntity deleteById(Long id) {
    FileEntity entity = super.get(id);
    if (entity != null) {
      getSession().delete(entity);
    }
    return entity;
  }
  
  @Override
  public Long sum(Long id) {
    Long result = new Long(0);
    Query query = getSession().createQuery("select sum(f.volume) from FileEntity f where f.bucket.id=:bucket");
    query.setParameter("bucket", id);
    Object temp = query.getSingleResult();
    if (temp instanceof Number) {
      Number number=(Number)temp;
      result=number.longValue();
    }
    return result;
  }
  
  @Override
  protected Class<FileEntity> getEntityClass() {
    return FileEntity.class;
  }
  
  @Autowired
  public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
}